package com.moba.controller;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.moba.domain.UserInfo;
import com.moba.emums.SmsTemplate;
import com.moba.service.UserInfoService;
import com.moba.utils.ResultUtils;
import com.moba.utils.sms.DySmsUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.validator.GenericValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.web3j.crypto.Keys;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/sms")
@Api(value = "")
public class SendMessageController extends BaseController {

    public static final String VERIFICATION_CODE = "verificationCode";

    public static final String MOBILE_VERI_CODE = "mobileVeriCode";

    public static final String MOBILE_CODE = "mobileCode";

    @Autowired
    UserInfoService userInfoService;

    @ApiOperation(value = "发送短信")
    @GetMapping(value = "/sendMsgCode")
    public Object sendMsgCode(HttpServletRequest request, String mobile,String temp) {

        String ret = "0";
        String msg = "";
        JSONObject datas = new JSONObject();
        HttpSession session = request.getSession();

        String ranNm = DySmsUtils.generateCheckPass();

        StringBuffer message = new StringBuffer("");
        String template_code = "";

        message.append("{\"code\":\"" + ranNm + "\"}");
        template_code = temp;

        boolean is_local = false;
        is_local = isLocal(request);
//        is_local = false;
        logger.info("======================is_local:"+is_local);
        if (StringUtils.isNotBlank(message.toString())) {
            String result = "1";
            if (!is_local) {// 不是本地，发送短信
                // result = SmsUtils.sendMessage(message, mobile);
                SendSmsResponse sendSmsResponse = DySmsUtils.sendMessage(message.toString(), mobile, template_code);
                if ("OK".equals(sendSmsResponse.getCode())) {
                    result = "0";
                }
            } else {// 如果是本地，则短信验证码为111111
                result = "0";
                ranNm = "111111";
            }

            logger.warn("==send result:{}", result);
            logger.warn("==send ranNm:{}", ranNm);
            if ("0".equals(result)) {
                session.setAttribute("mobileVeriCode", ranNm);
//                session.setAttribute("mobileCode", mobile);
                System.out.println("====mobileVeriCode:"+session.getAttribute("mobileVeriCode"));
                System.out.println("====mobileVeriCode:"+session.getAttribute("mobileVeriCode"));
                System.out.println("====mobileVeriCode:"+session.getAttribute("mobileVeriCode"));

                datas.put("veriCode", ranNm); // 测试
                ret = "1";
                msg = "发送成功";
            } else {
                ret = "0";
                msg = "发送失败，请稍后重试";
            }
        } else {
            ret = "0";
            msg = "发送失败，请稍后重试";
        }
        return ResultUtils.success(datas);

    }


    public boolean isLocal(HttpServletRequest request) {
        boolean isLocal = false;

        String ip = this.getIpAddr(request);
        if (StringUtils.equals("0:0:0:0:0:0:0:1", ip) || StringUtils.equals("127.0.0.1", ip)
                || StringUtils.startsWith(ip, "192.168.3.") || StringUtils.startsWith(ip, "192.168.1.")
                || StringUtils.startsWith(ip, "192.168.2.") || StringUtils.startsWith(ip, "192.168.0.")
                || StringUtils.startsWith(ip, "223.215.57.28") || StringUtils.startsWith(ip, "192.168.2.160")
                || StringUtils.startsWith(ip, "192.168.2.127")) {
            isLocal = true;
        }
        return isLocal;
    }

    public String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (StringUtils.isNotBlank(ip) && !"unknown".equalsIgnoreCase(ip) && StringUtils.contains(ip, ",")) {
            ip = StringUtils.split(ip, ",")[0];
        }
        if ((ip == null) || (ip.length() == 0) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if ((ip == null) || (ip.length() == 0) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if ((ip == null) || (ip.length() == 0) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }


}
